package com.example.usermanagement.vo;

import com.example.usermanagement.enums.ResponseStatus;
import com.example.usermanagement.exception.AuthErrorException;
import com.example.usermanagement.exception.ObjectNotException;
import com.example.usermanagement.exception.ParamErrorException;
import com.example.usermanagement.exception.ParamNotException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 统一输出模型
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ResultVO<T> {


    /**
     * 状态码
     */
    private String code;
    /**
     * 提示信息
     */
    private String msg;

    private T data;


    /**
     * 自定义成功返回提示信息
     * @param message
     */
    public ResultVO(String message){
        this.code = ResponseStatus.OK.getCode();
        this.msg = message;
    }

    public ResultVO(String code,String message){
        this.code = code;
        this.msg = message;
    }



    public ResultVO(T result){
        this.code = ResponseStatus.OK.getCode();
        this.msg = ResponseStatus.OK.getMsg();
        this.data = result;
    }



    public void setException(Exception exception) {
        this.code = CoreResult(exception);
        this.msg = exception.getMessage();
    }

    private static String CoreResult(Throwable throwable){
        if(throwable instanceof ParamNotException) {
            return ResponseStatus.PARAM_NOT.getCode();
        }
        if(throwable instanceof ParamErrorException){
            return ResponseStatus.PARAM_ERROR.getCode();
        }

        if(throwable instanceof AuthErrorException){
            return ResponseStatus.AUTH_ERROR_TOKEN.getCode();
        }

        if(throwable instanceof ObjectNotException){
            return ResponseStatus.OBJECT_NOT.getCode();
        }


        return  ResponseStatus.ERROR.getCode();
    }
}
